﻿using GBT.ManageEnties;
using GBT.ParamEntity;
using GBT.SystemBusinessCore;
using GBT.SystemEnties;
using GBT.Tool.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using Persistence.Core;
using SqlSugar;
using System;
using System.Data.SqlClient;
using System.Linq;

namespace QueryDataLogic.Core
{
    public class UserVerify
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        ConfigManage cm = new ConfigManage();
        QueryData qd = new QueryData();
        PersistenceData pd = new PersistenceData();
        SmsManage sm = new SmsManage();
        WXServiceAPI wxApi = new WXServiceAPI();
        BasicInfo bi = new BasicInfo();
        DataPaging dp = new DataPaging();

        /// <summary>
        /// 判断用户是否存在
        /// </summary>
        /// <param name="districtID"></param>
        /// <param name="mobile"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public bool IsUser(int districtID, string mobile, SqlSugarClient db)
        {
            try
            {
                var userList = db.Queryable<MealUser>().Where(t => t.DistrictID == districtID && t.mobile == mobile).ToList();
                if (userList.Count > 0)
                {
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                throw;
            }
        }

        /// <summary>
        /// 判断用户工号是否存在
        /// </summary>
        /// <param name="districtID"></param>
        /// <param name="mobile"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public bool IsUserNumber(int districtID, string Number, SqlSugarClient db)
        {
            try
            {
                var userList = db.Queryable<MealUser>().Where(t => t.DistrictID == districtID && t.Number == Number).ToList();
                if (userList.Count > 0)
                {
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                throw;
            }
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="districtID"></param>
        /// <returns></returns>
        public JObject GetUserList(int CurrentPage, int districtID)
        {
            JObject joResult = new JObject();
            try
            {
                string dbName = bi.GetDBName(districtID);

                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "SELECT mu.userID, mu.mobile, ab.number, ab.name, mu.nickName, mu.country, mu.province, mu.city, mu.[language], mu.isAdmin, mu.isAudit, mu.districtID, mu.isManager, mu.isTemporary " +
                    "FROM MealUser mu LEFT JOIN AddressBook ab ON mu.AddressBookID = ab.ID WHERE mu.districtID = @districtID "
                };

                comm.Parameters.AddWithValue("@districtID", districtID);

                JArray jaUser = qd.GetData(comm, dbName);
                if (jaUser.Count > 0)
                {
                    joResult = dp.PagingProcessing(CurrentPage, jaUser);
                }
                else
                {
                    joResult.Add("data", new JArray());
                    joResult.Add("message", "用户列表加载失败。");
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="mealUser"></param>
        /// <param name="totalNumber"></param>
        /// <param name="totalPage"></param>
        /// <returns></returns>
        public object GetUserInfo(System_MealUser mealUser, ref int totalNumber, ref int totalPage)
        {
            object result = null;
            try
            {
                var dbName = bi.GetDBName((int)mealUser.DistrictID);
                Manage_District district = new Manage_District();
                district.DistrictID = mealUser.DistrictID;
                district = bi.GetDistrictInfo(district);
                DbContext<MealUser> dbContext = new DbContext<MealUser>(dbName);
                var db = dbContext.Db;
                var mealUserList = db.Queryable<MealUser, AddressBook, UserStoredValue>((mu, ab, usv) => new object[]{
                    JoinType.Left, mu.AddressBookID == ab.ID,
                    JoinType.Left, mu.UserID == usv.UserID,
                })
                .Where((mu, ab, usv) => mu.DistrictID == mealUser.DistrictID)
                .WhereIF(mealUser.UserID != null, (mu, ab, usv) => mu.UserID == mealUser.UserID)
                .WhereIF(mealUser.AddressBookID != null, (mu, ab, usv) => mu.AddressBookID == mealUser.AddressBookID)
                .WhereIF(!string.IsNullOrEmpty(mealUser.Name), (mu, ab, usv) => ab.name.Contains(mealUser.Name))
                .WhereIF(!string.IsNullOrEmpty(mealUser.Number), (mu, ab, usv) => ab.Number.Contains(mealUser.Number))
                .WhereIF(!string.IsNullOrEmpty(mealUser.nickName), (mu, ab, usv) => mu.nickName.Contains(mealUser.nickName))
                .Select((mu, ab, usv) => new
                {
                    mu.UserID,
                    ab.Number,
                    ab.name,
                    ab.mobile,
                    usv.Value,
                    mu.nickName,
                    mu.isAdmin,
                    mu.isAudit,
                    mu.isManager,
                    mu.isTemporary,
                    mu.IsFinace,
                    mu.DistrictID,
                }).ToPageList(mealUser.PageIndex, mealUser.PageSize, ref totalNumber, ref totalPage);

                var mealUserListNew = mealUserList.Select(t => new {
                    t.UserID,
                    t.Number,
                    t.name,
                    t.mobile,
                    t.nickName,
                    t.Value,
                    IsAdmin = t.isAdmin,
                    IsAudit = t.isAudit,
                    IsManager = t.isManager == null ? false : t.isManager,
                    IsTemporary = t.isTemporary == null ? false : t.isTemporary,
                    IsFinace = t.IsFinace == null ? false : t.IsFinace,
                    t.DistrictID,
                    district.DistrictNumber,
                    district.DistrictName
                }).ToList();

                result = mealUserListNew;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.WriteLine(ex);
            }
            return result;
        }

        private object GetCompanyInfo(int districtID)
        {
            GBT.ManageBusinessCore.DbContext<Company> dbContext = new GBT.ManageBusinessCore.DbContext<Company>();
            var db = dbContext.Db;
            var companyInfo = db.Queryable<Company, District, Versions>((c, d, v) => new object[] {
                JoinType.Left, c.ID == d.CompanyID,
                JoinType.Left, c.VersionID == v.ID,
            }).Where((c, d, v) => d.DistrictID == districtID)
            .Select((c, d, v) => new {
                c.ID,
                c.Number,
                c.Name,
                c.reg_num,
                c.Address,
                c.Mobile,
                c.Tel,
                c.legal_representative,
                c.Remark,
                c.CreationTime,
                c.isAudit,
                VersionID = v.ID,
                VersionNumber = v.Number,
                VersionName = v.Name,
            })
            .First();
            return companyInfo;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="districtID"></param>
        /// <returns></returns>
        public JObject GetUserInfo(int districtID, string mobile)
        {
            JObject joResult = new JObject();
            try
            {
                string dbName = bi.GetDBName(districtID);
                GBT.SystemBusinessCore.DbContext<MealUser> dbContext = new GBT.SystemBusinessCore.DbContext<MealUser>(dbName);
                var db = dbContext.Db;

                var userInfo = db.Queryable<MealUser, AddressBook, UserStoredValue>((mu, ab, usv) => new object[] {
                    JoinType.Left, mu.AddressBookID == ab.ID,
                    JoinType.Left, mu.UserID == usv.UserID,
                })
                .Where((mu, ab, usv) => mu.mobile == mobile && mu.DistrictID == districtID)
                .Select((mu, ab, usv) => new
                {
                    userID = mu.UserID,
                    mu.mobile,
                    number = ab.Number,
                    ab.name,
                    usv.Value,
                    mu.nickName,
                    mu.country,
                    mu.province,
                    mu.city,
                    mu.language,
                    mu.isAdmin,
                    mu.isAudit,
                    districtID = mu.DistrictID,
                    mu.isManager,
                    mu.isTemporary,
                    mu.IsFinace,
                }).ToList();

                var userInfoNew = userInfo.Select(t => new {
                    t.userID,
                    t.mobile,
                    t.number,
                    t.name,
                    t.Value,
                    t.nickName,
                    t.country,
                    t.province,
                    t.city,
                    t.language,
                    t.isAdmin,
                    t.isAudit,
                    t.districtID,
                    t.isManager,
                    t.isTemporary,
                    t.IsFinace,
                    company = GetCompanyInfo(t.districtID),
                }).ToList();

                JArray jaUser = JArray.Parse(JsonConvert.SerializeObject(userInfoNew));
                if (jaUser.Count > 0)
                {
                    joResult.Add("data", jaUser);
                    joResult.Add("message", "用户验证成功。");
                    joResult.Add("state", true);
                }
                else
                {
                    joResult.Add("data", new JArray());
                    joResult.Add("message", "用户不存在，请注册用户。");
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 添加或修改用户信息
        /// </summary>
        /// <param name="joUserInfo"></param>
        /// <returns></returns>
        public JObject SetUserInfo(JObject joUserInfo)
        {
            logger.Info(joUserInfo.ToString());
            JObject joResult = new JObject();
            int ResultLine = 0;
            string mobile = (string)joUserInfo["mobile"];
            string Number = (string)joUserInfo["number"];
            string Name = (string)joUserInfo["name"];
            string nickName = (string)joUserInfo["nickName"];
            string country = (string)joUserInfo["country"];
            string province = (string)joUserInfo["province"];
            string city = (string)joUserInfo["city"];
            string language = (string)joUserInfo["language"];
            int districtID = (int)joUserInfo["districtID"];
            string jscode = (string)joUserInfo["jscode"];
            string openID = wxApi.getOpenID(jscode);//根据jscode获取到openID
            string dbName = bi.GetDBName(districtID);

            MealUser mealUser = new MealUser();
            mealUser.mobile = mobile;
            mealUser.Number = Number;
            mealUser.Name = Name;
            mealUser.nickName = nickName;
            mealUser.country = country;
            mealUser.province = province;
            mealUser.city = city;
            mealUser.language = language;
            mealUser.DistrictID = districtID;
            mealUser.OpenID = openID;
            AddressBook addressBook = new AddressBook();
            addressBook.DistrictID = districtID;
            addressBook.mobile = mobile;
            addressBook.Number = Number;
            addressBook.name = Name;
            addressBook.CreationDate = DateTime.Now;

            GBT.SystemBusinessCore.DbContext<MealUser> dbMealUser = new GBT.SystemBusinessCore.DbContext<MealUser>(dbName);
            var db = dbMealUser.Db;
            try
            {
                db.Ado.BeginTran();
                if (!bi.IsMobile(mobile, dbName) && !bi.IsNumber(districtID, Number, db))
                {
                    var addressBookID = db.Insertable(addressBook).ExecuteReturnIdentity();
                    mealUser.AddressBookID = addressBookID;
                }
                else if (bi.IsMobile(mobile, dbName) && !bi.IsNumber(districtID, Number, db))
                {
                    addressBook = db.Queryable<AddressBook>().Where(t => t.mobile == mobile && t.DistrictID == districtID).First();
                    addressBook.Number = Number;
                    addressBook.name = Name;
                    mealUser.AddressBookID = addressBook.ID;
                    //更新通讯录
                    db.Updateable(addressBook).ExecuteCommand();
                }
                else
                {
                    addressBook = db.Queryable<AddressBook>().Where(t => t.mobile == mobile && t.DistrictID == districtID).First();
                    mealUser.AddressBookID = addressBook.ID;
                }

                if (!IsUser(districtID, mobile, db) && !IsUserNumber(districtID, Number, db))
                {
                    ResultLine = dbMealUser.InsertReturnLineNumber(mealUser);

                    joResult.Add("data", ResultLine);
                    joResult.Add("message", "注册用户：" + mobile + " 成功。");
                    joResult.Add("state", "add");
                }
                else if (IsUser(districtID, mobile, db) && !IsUserNumber(districtID, Number, db))
                {
                    ResultLine = db.Updateable(mealUser).UpdateColumns(t => new { t.Number, t.Name }).Where(t => t.mobile == mobile && t.DistrictID == districtID).ExecuteCommand();

                    joResult.Add("data", ResultLine);
                    joResult.Add("message", "注册用户：" + mobile + " 成功。");
                    joResult.Add("state", "modify");
                }
                else
                {
                    joResult.Add("data", ResultLine);
                    joResult.Add("message", "注册用户：" + mobile + " 成功。");
                    joResult.Add("state", "modify");
                }

                db.Ado.CommitTran();

                //返回用户信息 用于保存到微信小程序端本地
                JObject joUser = new JObject();
                joUser = GetUserInfo(districtID, mobile);
                joResult.Add("userInfo", joUser);
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", 0);
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", "error");
            }
            return joResult;
        }

        /// <summary>
        /// 获取邀请码
        /// </summary>
        /// <param name="districtID"></param>
        /// <returns></returns>
        public JObject GetInvitationCode(int districtID)
        {
            JObject joResult = new JObject();
            try
            {
                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "SELECT code,date FROM InvitationCode WHERE id = (select max(id) from InvitationCode where districtID = @districtID) "
                };
                comm.Parameters.AddWithValue("@districtID", districtID);
                JArray jaInvitationCode = qd.GetData(comm, "MealManage");
                if (jaInvitationCode.Count > 0)
                {
                    joResult.Add("data", jaInvitationCode);
                    joResult.Add("message", "获取邀请码成功。");
                    joResult.Add("state", true);
                }
                else
                {
                    joResult.Add("data", new JArray());
                    joResult.Add("message", "邀请码不存在，请联系管理员。");
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 判断邀请码是否存在
        /// </summary>
        /// <param name="code">邀请码</param>
        /// <returns></returns>
        private bool IsCode(int code)
        {
            try
            {
                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "SELECT ID FROM InvitationCode WHERE code = @code "
                };

                comm.Parameters.AddWithValue("@code", code);

                JArray jaUser = qd.GetData(comm, "MealManage");

                if (jaUser.Count > 0)
                {
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                throw;
            }
        }

        /// <summary>
        /// 生成邀请码
        /// </summary>
        /// <returns></returns>
        public int GenerateCode()
        {
            Random rad = new Random();//实例化随机数产生器rad；
            int value = rad.Next(1000, 100000);//用rad生成大于等于1000，小于等于99999的随机数；
            //string code = value.ToString(); //转化为字符串；
            //递归判断如果邀请码存在则重新生成
            if (IsCode(value))
            {
                GenerateCode();
            }

            return value;
        }

        /// <summary>
        /// 生成邀请码
        /// </summary>
        /// <param name="districtID"></param>
        /// <returns></returns>
        public JObject SetInvitationCode(JObject joParam)
        {
            JObject joResult = new JObject();
            int ResultLine = 0;
            try
            {
                int oldCode = (int)joParam["code"];
                int districtID = (int)joParam["districtID"];
                int value = GenerateCode();//生成不重复的邀请码
                JObject joInvitationCode = new JObject();
                joInvitationCode = GetInvitationCode(districtID);
                if (joInvitationCode.Property("data") != null)
                {
                    JArray jaInvitationCode = (JArray)joInvitationCode["data"];
                    if (jaInvitationCode.Count > 0)
                    {
                        DateTime dtLast = ((DateTime)jaInvitationCode[0]["date"]).AddHours(5);

                        if (DateTime.Now.ToFileTime() > dtLast.ToFileTime())
                        {
                            SqlCommand comm = new SqlCommand()
                            {
                                CommandText = "UPDATE InvitationCode SET code = @code,date=@date WHERE code = @oldCode AND districtID = @districtID "
                            };

                            comm.Parameters.AddWithValue("@code", value);
                            comm.Parameters.AddWithValue("@date", DateTime.Now.ToString());
                            comm.Parameters.AddWithValue("@oldCode", oldCode);
                            comm.Parameters.AddWithValue("@districtID", districtID);

                            ResultLine = pd.ExeSqlCode(comm, "MealManage");
                            joResult.Add("data", ResultLine);
                            joResult.Add("message", "生成邀请码：" + value.ToString() + " 成功。");
                            joResult.Add("state", true);
                            joResult.Add("code", value);
                        }
                        else
                        {
                            joResult.Add("data", ResultLine);
                            joResult.Add("message", "你操作太频繁了，请在 " + dtLast.ToString() + " 后再试。");
                            joResult.Add("state", false);
                            joResult.Add("code", (int)jaInvitationCode[0]["code"]);
                        }
                    }
                    else
                    {
                        SqlCommand comm = new SqlCommand()
                        {
                            CommandText = "INSERT INTO InvitationCode(code,districtID) VALUES(@code,@districtID) "
                        };

                        comm.Parameters.AddWithValue("@code", value);
                        comm.Parameters.AddWithValue("@districtID", districtID);

                        ResultLine = pd.ExeSqlCode(comm, "MealManage");
                        joResult.Add("data", ResultLine);
                        joResult.Add("message", "生成邀请码：" + value.ToString() + " 成功。");
                        joResult.Add("state", true);
                        joResult.Add("code", value);
                    }
                }
                else
                {
                    SqlCommand comm = new SqlCommand()
                    {
                        CommandText = "INSERT INTO InvitationCode(code,districtID) VALUES(@code,@districtID) "
                    };

                    comm.Parameters.AddWithValue("@code", value);
                    comm.Parameters.AddWithValue("@districtID", districtID);

                    ResultLine = pd.ExeSqlCode(comm, "MealManage");
                    joResult.Add("data", ResultLine);
                    joResult.Add("message", "生成邀请码：" + value.ToString() + " 成功。");
                    joResult.Add("state", true);
                    joResult.Add("code", value);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", 0);
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 短信验证
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public JObject SmsVerify(string mobile)
        {
            JObject joResult = new JObject();
            try
            {
                Random rad = new Random();//实例化随机数产生器rad；
                int value = rad.Next(1000, 10000);//用rad生成大于等于1000，小于等于9999的随机数；
                string code = value.ToString(); //转化为字符串；
                bool isFinish = false;
                isFinish = sm.SendManage(mobile, code);
                if (isFinish)
                {
                    joResult.Add("message", "验证码发送成功");
                    joResult.Add("code", code);//客户端验证，验证码的正确性。
                    joResult.Add("state", true);
                }
                else
                {
                    joResult.Add("message", "手机号码无效，请重新输入");
                    joResult.Add("code", code);//客户端验证，验证码的正确性。
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("message", "验证码发送失败，请一分钟后重新发送。");
                joResult.Add("code", "");//客户端验证，验证码的正确性。
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 手机号码验证
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public JObject MobileVerify(int districtID, string mobile)
        {
            JObject joResult = new JObject();
            try
            {
                string dbName = bi.GetDBName(districtID);

                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "SELECT id,name,mobile FROM AddressBook WHERE mobile = @mobile AND districtID = @districtID "
                };

                comm.Parameters.AddWithValue("@mobile", mobile);
                comm.Parameters.AddWithValue("@districtID", districtID);

                JArray ja = qd.GetData(comm, dbName);
                if (ja.Count > 0)
                {
                    joResult.Add("data", ja);
                    joResult.Add("message", "手机号码验证成功。");
                    joResult.Add("state", true);
                }
                else
                {
                    joResult.Add("data", new JArray());
                    joResult.Add("message", "手机号码输入错误或不在通讯录中，请重新输入或联系管理员。");
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 工号验证
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public JObject UserNumberVerify(int districtID, string mobile, string Number)
        {
            JObject joResult = new JObject();
            try
            {
                string dbName = bi.GetDBName(districtID);

                GBT.SystemBusinessCore.DbContext<MealUser> dbContext = new GBT.SystemBusinessCore.DbContext<MealUser>(dbName);
                var systemDb = dbContext.Db;
                var users = dbContext.GetList(t => t.DistrictID == districtID && t.Number == Number && t.mobile != mobile);
                var userJson = JsonConvert.SerializeObject(users);
                if (users.Count > 0)
                {
                    joResult.Add("data", JArray.Parse(userJson));
                    joResult.Add("message", "工号已存在");
                    joResult.Add("state", false);
                }
                else
                {
                    joResult.Add("data", new JArray());
                    joResult.Add("message", "");
                    joResult.Add("state", true);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 邀请码验证
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public JObject InvitationCodeVerify(JObject joParam)
        {
            JObject joResult = new JObject();
            try
            {
                int code = (int)joParam["code"];

                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "select ic.id,ic.code,d.districtID,d.districtNumber,d.districtName " +
                                  "from InvitationCode ic inner join District d on ic.DistrictID = D.DistrictID  WHERE ic.code = @code"
                };

                comm.Parameters.AddWithValue("@code", code);

                JArray ja = qd.GetData(comm, "MealManage");
                if (ja.Count > 0)
                {
                    joResult.Add("data", ja);
                    joResult.Add("message", "邀请码验证成功。");
                    joResult.Add("state", true);
                }
                else
                {
                    joResult.Add("data", new JArray());
                    joResult.Add("message", "邀请码输入错误，请重新输入。");
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 密码验证（桌面端专用）
        /// </summary>
        /// <param name="joParam"></param>
        /// <returns></returns>
        public JObject PasswordVerify(JObject joParam)
        {
            JObject joResult = new JObject();
            try
            {
                logger.Info(joParam);
                string Number = (string)joParam["Number"];
                string password = (string)joParam["password"];
                int districtID = 1;
                if (joParam.Property("districtID") != null)
                {
                    districtID = (int)joParam["districtID"];
                }
                string dbName = bi.GetDBName(districtID);

                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "SELECT Name, mobile FROM MealUser WHERE Number = @Number AND " +
                    "Number <> '' AND ISNULL(password,'') = @password AND isAdmin = 1"
                };

                comm.Parameters.AddWithValue("@Number", Number.Trim());
                comm.Parameters.AddWithValue("@password", password.Trim());

                JArray ja = qd.GetData(comm, dbName);
                if (ja.Count > 0)
                {
                    joResult.Add("data", ja);
                    joResult.Add("message", "用户登录成功");
                    joResult.Add("state", true);
                }
                else
                {
                    joResult.Add("data", new JArray());
                    joResult.Add("message", "用户登录失败，请确认用户或密码是否正确");
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 修改密码（桌面端专用）
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public JObject ModifyPassword(JObject joParam)
        {
            JObject joResult = new JObject();
            int ResultLine = 0;
            try
            {
                logger.Info(joParam);
                string mobile = (string)joParam["mobile"];
                string oldPassword = (string)joParam["oldPassword"];
                string password = (string)joParam["password"];
                int districtID = 1;
                if (joParam.Property("districtID") != null)
                {
                    districtID = (int)joParam["districtID"];
                }

                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "UPDATE MealUser SET [password] = @password WHERE mobile = @mobile AND ISNULL([password],'') = @oldPassword "
                };

                comm.Parameters.AddWithValue("@mobile", mobile);
                comm.Parameters.AddWithValue("@oldPassword", oldPassword);
                comm.Parameters.AddWithValue("@password", password);

                ResultLine = pd.ExeSqlCode(comm, "MealSystem");
                if (ResultLine > 0)
                {
                    joResult.Add("data", ResultLine);
                    joResult.Add("message", "修改密码成功");
                    joResult.Add("state", true);
                }
                else
                {
                    joResult.Add("data", ResultLine);
                    joResult.Add("message", "修改密码失败，请确认手机号或原密码是否输入正确");
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 获取桌面端注册信息（桌面端专用 多公司版本）
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public JObject GetRegisterInfo(JObject joParam)
        {
            JObject joResult = new JObject();
            try
            {
                logger.Info(joParam);
                string code = (string)joParam["code"];
                string mobile = (string)joParam["mobile"];
                string password = (string)joParam["password"];
                string dbName = bi.GetDBNameToCode(code);

                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "SELECT userID,mobile,number,name,nickName,country,province,city,[language],isAdmin,isAudit,districtID,isManager,isTemporary " +
                    "FROM MealUser WHERE mobile = @mobile AND ISNULL(password,'') = @password AND isAdmin = 1"
                };

                comm.Parameters.AddWithValue("@mobile", mobile);
                comm.Parameters.AddWithValue("@password", password);

                JArray ja = qd.GetData(comm, dbName);
                if (ja.Count > 0)
                {
                    joResult.Add("data", ja);
                    joResult.Add("message", "获取注册信息成功");
                    joResult.Add("state", true);
                }
                else
                {
                    joResult.Add("data", new JArray());
                    joResult.Add("message", "获取注册信息失败，请确认是否已在微信端注册");
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 用户登录验证（桌面端专用 管理员）
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public JObject UserLoginVerify(JObject joParam)
        {
            JObject joResult = new JObject();
            try
            {
                logger.Info(joParam);
                string Number = (string)joParam["Number"];
                string password = (string)joParam["password"];
                int districtID = (int)joParam["districtID"];
                string dbName = bi.GetDBName(districtID);

                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "SELECT Name, mobile FROM MealUser WHERE Number = @Number AND Number <> '' AND ISNULL(password,'') = @password AND isAdmin = 1"
                };

                comm.Parameters.AddWithValue("@Number", Number);
                comm.Parameters.AddWithValue("@password", password);

                JArray ja = qd.GetData(comm, dbName);
                if (ja.Count > 0)
                {
                    joResult.Add("data", ja);
                    joResult.Add("message", "用户登录成功");
                    joResult.Add("state", true);
                }
                else
                {
                    joResult.Add("data", new JArray());
                    joResult.Add("message", "用户登录失败，请确认用户或密码是否正确");
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 用户登录验证（桌面端专用）
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public JObject LoginVerify(JObject joParam)
        {
            JObject joResult = new JObject();
            try
            {
                logger.Info(joParam);
                string Number = (string)joParam["Number"];
                string password = (string)joParam["password"];
                int districtID = (int)joParam["districtID"];
                string dbName = bi.GetDBName(districtID);

                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "SELECT mu.UserID, ab.Number, ab.Name, mu.nickName, mu.mobile, mu.isAdmin, mu.isManager, mu.isAudit, mu.DistrictID, mu.IsFinace FROM MealUser  mu " +
                    "Left join AddressBook ab on mu.AddressBookID = ab.ID " +
                    "WHERE ab.Number = @Number AND ab.Number <> '' AND ISNULL(mu.password,'') = @password "
                };

                comm.Parameters.AddWithValue("@Number", Number);
                comm.Parameters.AddWithValue("@password", password);

                JArray ja = qd.GetData(comm, dbName);
                if (ja.Count > 0)
                {
                    for (int index = 0; index < ja.Count; index++)
                    {
                        ja[index]["Company"] = JObject.Parse(JsonConvert.SerializeObject(GetCompanyInfo(districtID)));
                    }
                    joResult.Add("data", ja);
                    joResult.Add("message", "用户登录成功");
                    joResult.Add("state", true);
                }
                else
                {
                    joResult.Add("data", new JArray());
                    joResult.Add("message", "用户登录失败，请确认用户或密码是否正确");
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }

        /// <summary>
        /// 修改用户密码（桌面端专用）
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public JObject ModifyUserPassword(JObject joParam)
        {
            JObject joResult = new JObject();
            int ResultLine = 0;
            try
            {
                logger.Info(joParam);
                string mobile = (string)joParam["mobile"];
                string oldPassword = (string)joParam["oldPassword"];
                string password = (string)joParam["password"];
                int districtID = (int)joParam["districtID"];
                string dbName = bi.GetDBName(districtID);

                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "UPDATE MealUser SET [password] = @password WHERE mobile = @mobile AND ISNULL([password],'') = @oldPassword "
                };

                comm.Parameters.AddWithValue("@mobile", mobile);
                comm.Parameters.AddWithValue("@oldPassword", oldPassword);
                comm.Parameters.AddWithValue("@password", password);

                ResultLine = pd.ExeSqlCode(comm, dbName);
                if (ResultLine > 0)
                {
                    joResult.Add("data", ResultLine);
                    joResult.Add("message", "修改密码成功");
                    joResult.Add("state", true);
                }
                else
                {
                    joResult.Add("data", ResultLine);
                    joResult.Add("message", "修改密码失败，请确认手机号或原密码是否输入正确");
                    joResult.Add("state", false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult.Add("data", new JArray());
                joResult.Add("message", ex.Message + "\r\n" + ex.StackTrace);
                joResult.Add("state", false);
            }
            return joResult;
        }
    }
}
